<template>
  <el-main>
    <!--搜索栏-->
    <el-form v-model="searchParam" label-width="80px" :inline="true" size="default">
      <el-form-item>
        <el-input placeholder="请输入用户昵称" v-model="searchParam.nickName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="请输入电话" v-model="searchParam.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchBtn" icon="Search">搜索</el-button>
        <el-button @click="resetBtn" icon="Close" type="danger" plain>重置</el-button>
        <el-button type="primary" @click="addBtn" v-permission="['sys:user:add']" icon="Plus">新增</el-button>
      </el-form-item>
    </el-form>
    <!--表格数据-->
    <el-table :data="tableList" border stripe :height="tableHeight">
      <el-table-column prop="nickName" label="姓名"></el-table-column>
      <el-table-column prop="sex" label="性别">
        <template #default="scope">{{ scope.row.sex == '0' ? '男' : '女' }}</template>
      </el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="userName" label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" @click="editBtn(scope.row)" icon="Edit">编辑</el-button>
          <el-button type="warning" @click="resetPassword(scope.row.userId)" icon="Setting">重置密码</el-button>
          <el-button type="danger" @click="deleteBtn(scope.row.userId)" icon="Delete">删除</el-button>
          <el-button type="danger" style="display: none">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
        style="padding-top: 20px"
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="searchParam.currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="searchParam.pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="searchParam.total" background

    >
    </el-pagination>
    <!--新增弹框-->
    <SysDialog
        :title="dialog.title"
        :width="dialog.width"
        :height="dialog.height"
        :visible="dialog.visible"
        style="padding-right: 40px"
        @on-c-lose="onClose"
        @on-confirm="commit"
    >
      <template v-slot:content>
        <el-form :model="userModel" ref="addRef" :rules="rules" label-width="80px" :inline="false" size="default">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="nickName" label="姓名" id="nickNameItem">
                <!--input如果不绑定响应式数据会出现不能输入的现象-->
                <el-input v-model="userModel.nickName" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="phone" label="电话">
                <el-input v-model="userModel.phone" placeholder="请输入电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="email" label="邮箱">
                <el-input v-model="userModel.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="tags=='0'?12:24">
              <el-form-item prop="username" label="帐户">
                <el-input
                    v-model="userModel.username"
                    placeholder="请输入登陆帐户"
                    ref="userNameInput"
                    :disabled="tags=='1'"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0" v-if="tags=='0'">
              <el-form-item prop="password" label="密码">
                <el-input v-model="userModel.password" placeholder="请输入登陆密码" show-password></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="roleId" label="角色">
                <select-checked
                    :options="options"
                    @selected="selected"
                    ref="selectRef"
                    :bindValue="bindValue"
                >
                </select-checked>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="sex" label="性别">
                <el-radio-group v-model="userModel.sex">
                  <el-radio :label="'0'">男</el-radio>
                  <el-radio :label="'1'">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </SysDialog>
  </el-main>
</template>

<script setup lang="ts">
import useDialog from '@/hocks/useDialog.ts'
import {nextTick, onMounted, reactive, ref} from "vue";
import SysDialog from "@/components/SysDialog.vue";
import type {FormInstance, FormRules} from "element-plus";
import {
  addApi,
  checkUserNameApi,
  delApi,
  editApi,
  getListApi,
  getRoleListApi,
  resetPasswordApi
} from "@/api/user";
import {ElMessage} from 'element-plus'
import type {SysUser, UserParam} from "@/api/user/UserModel.ts";
import SelectChecked from "@/components/SelectChecked.vue";
import {getSelectApi} from "@/api/role";
import type {Result} from "@/http";
import useInstance from "@/hocks/useInstance.ts";
//获取自定义组件Dialog要用到的方法和变量
const {dialog, onClose, onShow} = useDialog()
//搜索条件数据模型
const searchParam: UserParam = reactive({
  nickName: '',
  phone: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
//用户数据模型用于新增和编辑
const userModel: SysUser = reactive({
  userId: '',
  username: '',
  password: '',
  phone: '',
  email: '',
  sex: '',
  nickName: '',
  roleId: ''
})
//表格高度变量
const tableHeight = ref(0)
//新增表单对象ID
const addRef = ref<FormInstance>()
//下拉选框对象ID
const selectRef = ref()//下拉列表对象
//表单验证规则
const rules = reactive<FormRules>({
  nickName: [{
    required: true,
    message: '请输入姓名',
    trigger: ['blur', 'change'],
  }],
  sex: [{
    required: true,
    message: '请选择性别',
    trigger: ['blur', 'change']
  }],
  phone: [{
    required: true,
    message: '请输入电话，且为数字',
    trigger: ['blur', 'change'],
  }],
  roleId: [{
    required: true,
    message: '请选择角色',
    trigger: ['blur', 'change'],
  }],
  username: [{
    required: true,
    message: '请输入帐户',
    trigger: ['blur', 'change']
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['blur', 'change']
  }]
})
//搜索按钮点击事件
const searchBtn = () => {
  getList()
}
//重置按钮点击事件
const resetBtn = () => {
  searchParam.nickName = ''
  searchParam.phone = ''
  searchParam.currentPage = 1
  getList()
}
//0:新增操作，1：编辑操作
const tags = ref('')
//绑定数据
const bindValue = ref([])
//接收后端返回的roleList
const roleIds = ref('')
const userNameInput = ref()
const checkUserName = async () => {
  if (tags.value == '0') {
    let res = await checkUserNameApi(userModel.userName)
    if (res && res.code == 200) {
      if (res.data) {
        ElMessage.error("用户名已存在！")
        userNameInput.value.focus()
        return
      }
    }
  }
}
//新增按钮点击事件
const addBtn = () => {
  tags.value = '0'
  dialog.title = '新增用户'
  dialog.height = 200
  //显示弹框
  onShow()
  //清空下拉数据
  options.value = []
  bindValue.value = []
  //获取下拉数据
  getSelect()
  nextTick(() => {
    selectRef.value.clear()
    //清空表单
    addRef.value?.resetFields()
  })
}
//获取角色列表
const getRoleList = async (userId: string) => {
  let res = await getRoleListApi(userId)
  if (res && res.code == 200) {
    bindValue.value = res.data
    roleIds.value = res.data.join(',')
  }
}
//编辑按钮点击事件
const editBtn = async (row: SysUser) => {
  tags.value = '1'
  dialog.title = '编辑用户'
  dialog.height = 230
  //清空下拉数据
  options.value = []
  bindValue.value = []
  //获取下拉数据
  await getSelect()
  //查询角色ID
  await getRoleList(row.userId)
  //显示弹框
  onShow()
  //这里的nextTick不能加await
  nextTick(() => {
    //数据回显
    Object.assign(userModel, row)
    userModel.roleId = roleIds.value
    userModel.password = ''
  }).then(r => console.log(r))
  //清空表单
  addRef.value?.resetFields()
}

const {global} = useInstance()
//删除按钮点击事件
const deleteBtn = async (userId: string) => {
  const confirm = await global.$myConfirm('确定删除吗？')
  if (confirm) {
    let res = await delApi(userId)
    if (res && res.code == 200) {
      ElMessage.success(res.msg)
      await getList()
    }
  }
}
//重置密码按钮点击事件
const resetPassword = async (userId: string) => {
  const confirm = await global.$myConfirm('确定重置密码为[666]吗？')
  if (confirm) {
    let res = await resetPasswordApi({userId: userId})
    if (res && res.code == 200) {
      ElMessage.success(res.msg)
    }
  }
}
//表格数据变量
const tableList = ref([])
//获取用户列表
const getList = async () => {
  let res = await getListApi(searchParam)
  if (res && res.code == 200) {
    tableList.value = res.data.records
    //设置分页总条数
    searchParam.total = res.data.total
  }
}
//页容量改变时触发
const sizeChange = (size: number) => {
  searchParam.pageSize = size
  getList()
}
//页数改变时触发
const currentChange = (page: number) => {
  searchParam.currentPage = page
  getList()
}
//加载动作
onMounted(() => {
  nextTick(function () {
    tableHeight.value = window.innerHeight - 310
  })
  getList()
})
//提交点击事件
const commit = () => {
  checkUserName()
  addRef.value?.validate(async (valid) => {
    if (valid) {
      let res: Result
      if (tags.value == '0') {
        res = await addApi(userModel)
      } else {
        res = await editApi(userModel)
      }
      if (res && res.code == 200) {
        ElMessage.success(res.msg)
        await getList()
        onClose()
      }
    }
  })
}
//下拉选框选中事件
const selected = (value: Array<string | number>) => {
  userModel.roleId = value.join(',')
}
//查询角色下拉数据
const getSelect = async () => {
  let res = await getSelectApi()
  if (res && res.code == 200) {
    options.value = res.data
  }
}
//下拉选框元素变量
const options = ref([
  {
    value: 'Beijing',
    label: 'Beijing',
  },
  {
    value: 'Shanghai',
    label: 'Shanghai',
  },
  {
    value: 'Nanjing',
    label: 'Nanjing',
  },
  {
    value: 'Chengdu',
    label: 'Chengdu',
  },
  {
    value: 'Shenzhen',
    label: 'Shenzhen',
  },
  {
    value: 'Guangzhou',
    label: 'Guangzhou',
  },
])
</script>

<style scoped>

</style>
